var Game = {
    first: 14,
    last: 39,
    nextNumber: 1
};

Game.generateArray = function() {
    
    var initArr = [],
        i;

    for (i = 1; i < Game.first; i++) {
        initArr.push(i);
    }

    for (i = Game.last; i <= 50; i++) {
        initArr.push(i);
    }

    initArr.sort(function() {
        return Math.random() > 0.5 ? -1 : 1;
    });

    return initArr;   
}

Game.init = function() {

    var initArr = Game.generateArray(),
        i, j;

    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            var li = document.createElement("li");
            li.textContent = initArr[i*5+j];
            Game.el.appendChild(li);
        }
    }
};

Game.start = function() {

    var border = document.querySelector(".border"),
        resetBtn = document.querySelector(".reset"),
        hint = document.querySelector(".hint"),
        li, duration;

    resetBtn.addEventListener("click", function() {
        Game.reset();
    });

    border.addEventListener("click", function(e) {

        if (e.target && e.target.nodeName === "LI") {

            li = e.target;

            if (li.textContent != Game.nextNumber) {

                // change background to RED for attention
                hint.style.background = "red";
                return;
            
            } else {

                // record the start time
                if (Game.nextNumber == 1) {
                    Game.startTime = new Date().getTime();
                }

                Game.nextNumber++;

                if (Game.nextNumber <= 50) {
                    hint.style.background = "#dd5862";
                    hint.textContent = Game.nextNumber;
                }
            }

            if (Game.first < Game.last) {
                li.textContent = Game.first++;
            } else {
                li.style.opacity = 0;
            }

            Game.checkFinish();
        }
    });
};

Game.checkFinish = function() {

    if (Game.nextNumber == 51) {
        Game.finishTime = new Date().getTime();
        duration = (Game.finishTime - Game.startTime) / 1000;
        swal("Good Job",
             "You used " + duration.toFixed(4) + " second!",
             "success");
        Game.reset();
    }
}

Game.reset = function() {

    var lis = document.querySelectorAll("li"),
        hint = document.querySelector(".hint"),
        initArr = Game.generateArray();

    for (var i = 0, len = lis.length; i < len; i++) {
        lis[i].textContent = initArr[i];
        lis[i].style.opacity = 1;
    }

    Game.first = 14;
    Game.last = 39;
    Game.nextNumber = 1;
    hint.textContent = 1;
    hint.style.background = "#dd5862";
};

window.onload = function() {
    Game.el = document.querySelector(".border");
    Game.init();
    Game.start();
};